#!/usr/bin/python

import sys
import commands
import gdata.docs.service
import gdata.photos.service
import gdata.media
import gdata.geo
import os
import keychain
import mimetypes

photoalbum = -1

def passwordPrompt() :
        CocoaDialog = "\"%s/Contents/Resources/CocoaDialog.app/Contents/MacOS/CocoaDialog\" " % (sys.argv[1],)
        cmd = CocoaDialog + " standard-inputbox --title \"Google Docs Uploader\" --no-newline --informative-text \"Enter your Google Docs Username\" --no-cancel --float"
        results = commands.getoutput(cmd)
        name = results.split('\n')[1]
        cmd = CocoaDialog + " standard-inputbox --title \"Google Docs Uploader\" --no-newline --informative-text \"Enter password for "+name+"\" --no-cancel --float --no-show"
        results = commands.getoutput(cmd)
        password = results.split('\n')[1]
        credentials = [name, password]
        return credentials

def getPassword() :
	keychainaccess = keychain.Keychain();
	result = keychainaccess.getserviceaccount('login', "Google Docs Uploader")
	if type(result) == type({'account':'foo'}):
		credentials = [result['account'], result['password']]
	else :
		print "Couldn't find login credentials.  Asking..."
                credentials = passwordPrompt()
	keychainaccess.setgenericpassword('login', credentials[0], credentials[1], "Google Docs Uploader")
	return credentials

def gd_client_login(gd_client, credentials) :
        gd_client.email = credentials[0]
        gd_client.password = credentials[1]
        gd_client.source = 'gdocsuploader-1.3'
        try :
                gd_client.ProgrammaticLogin()
        except gdata.service.BadAuthentication :
                displayMessage("Unable to log into Google", "You may want to check your login credentials using the 'Keychain Access' program")
                exit()

def displayMessage(msg_title, msg_desc) :
	resources = sys.argv[1] + "/Contents/Resources/"
	CocoaDialog = "\"%s/Contents/Resources/CocoaDialog.app/Contents/MacOS/CocoaDialog\" " % (sys.argv[1],)
	cmd = CocoaDialog + " msgbox --text \"" + msg_title + "\" --informative-text \""+msg_desc+"\" --float --button1 \"Ok\""
	commands.getoutput(cmd)
        
def uploadDocument(filename, credentials):
        CocoaDialog = "\"%s/Contents/Resources/CocoaDialog.app/Contents/MacOS/CocoaDialog\" " % (sys.argv[1],)
        
        ext = os.path.splitext(filename)[1][1:].upper()
	base = os.path.basename(filename)
        mime_type_guess = mimetypes.guess_type(filename)[0]
	supported_docs = ['DOC','ODT','SWX','TXT','RTF','HTM','HTML']
	supported_sheets = ['ODS','XLS','CSV','TSV']
	supported_presentations = ['PPT','PPS']
        print gdata.photos.service.SUPPORTED_UPLOAD_TYPES
	if ext.lower() in gdata.photos.service.SUPPORTED_UPLOAD_TYPES :
		try :
			gd_client = gdata.photos.service.PhotosService()
		except ImportError :
			displayMessage("Unable to load ElementTree", "You may try installing it at http://effbot.org/zone/element-index.htm")
			exit()
	else :
		try :
			gd_client = gdata.docs.service.DocsService()
		except ImportError :
			displayMessage("Unable to load ElementTree", "You may try installing it at http://effbot.org/zone/element-index.htm")
			exit()

        gd_client_login(gd_client, credentials)
    
	url = False
	if ext in supported_docs :
		ms = gdata.MediaSource(file_path = filename, content_type = gdata.docs.service.SUPPORTED_FILETYPES[ext])
		entry = gd_client.UploadDocument(ms,base)
		url = entry.GetAlternateLink().href
	elif ext in supported_sheets :
		ms = gdata.MediaSource(file_path=filename, content_type=gdata.docs.service.SUPPORTED_FILETYPES[ext])
		entry = gd_client.UploadSpreadsheet(ms,base)
		url = entry.GetAlternateLink().href		
	elif ext in supported_presentations :
		ms = gdata.MediaSource(file_path = filename, content_type = gdata.docs.service.SUPPORTED_FILETYPES[ext])
		entry = gd_client.UploadPresentation(ms,base)
		url = entry.GetAlternateLink().href
	elif ext.lower() in gdata.photos.service.SUPPORTED_UPLOAD_TYPES :
		feed = gd_client.GetUserFeed()
                global photoalbum
                if photoalbum == -1 :
                        items = " --items "
                        for entry in feed.entry :
                                items += " \"%s\"" % entry.title.text
                        cmd = CocoaDialog + " dropdown --title \"Select Album\" --text \"Select album for photo upload \" " + items + " --button1 \"Select\" --button2 \"Cancel\" --button3 \"New Album\" --float"
                        results = commands.getoutput(cmd)
                        option = results.split('\n')[0]
                else :
                        option = 100
                if option == '' or int(option) == 2 :
                        exit()
                elif int(option) == 1 :
                        albumindex = results.split('\n')[1]
                        photoalbum = int(albumindex)
                        album = feed.entry[int(albumindex)]
                        album_url = '/data/feed/api/user/%s/album/%s' % ('default', album.name.text)
                        entry = gd_client.InsertPhotoSimple(album_url, 'filename', '', filename, content_type=mime_type_guess)
                        url = entry.link[1].href
                elif int(option) == 100 :
                        album = feed.entry[photoalbum]
                        album_url = '/data/feed/api/user/%s/album/%s' % ('default', album.name.text)
                        entry = gd_client.InsertPhotoSimple(album_url, 'filename', '', filename, content_type=mime_type_guess)
                        url = entry.link[1].href
                elif int(option) == 3 :
                        cmd = CocoaDialog + " standard-inputbox --title \"Create New Picassa Web Album\" --no-newline --informative-text \"Enter the title of the new album\" --no-cancel --float"
                        results = commands.getoutput(cmd)
                        name = results.split('\n')[1]
                        album = gd_client.InsertAlbum(name, '', access='private')
                        album_url = '/data/feed/api/user/%s/album/%s' % ('default', album.name.text)
                        entry = gd_client.InsertPhotoSimple(album_url, 'filename', '', filename, content_type=mime_type_guess)
                        url = entry.link[1].href
                else :
                        displayMessage("Error", "Unknown selection error. option = "+option+" Please report this.")
                        exit()
        elif len(ext) > 0 :
		displayMessage("Unsupported Filetype", ext+" documents aren't a supported filetype")
		exit()
        return url

def goToDoc(url) :
        CocoaDialog = "\"%s/Contents/Resources/CocoaDialog.app/Contents/MacOS/CocoaDialog\" " % (sys.argv[1],)
        if url :
		cmd = CocoaDialog + " yesno-msgbox --title \"Google Docs Uploader: Success!\" --text \"Open the document in a web browser?\" --no-cancel"
		results = commands.getoutput(cmd)
		if int(results) == 1 :
			cmd = "osascript -e 'open location \""+url+"\"'"
			commands.getoutput(cmd)
	else :
		displayMessage("Unknown upload status", "Something might have gone wrong with the upload")

def main():
        print sys.argv
        CocoaDialog = "\"%s/Contents/Resources/CocoaDialog.app/Contents/MacOS/CocoaDialog\" " % (sys.argv[1],)
	credentials = getPassword()
	
        if len(sys.argv) == 3 :
                filename = sys.argv[2]
                url = uploadDocument(filename, credentials)
                goToDoc(url)
        elif len(sys.argv) >= 3 :
                results = [0,0]
                for filename in sys.argv[2:] :
                        result = uploadDocument(filename, credentials)
                        if result :
                                results[0] += 1
                        else :
                                results[0] += 1
                if results[0] > 0 :
                        if results[1] == 1 :
                                failmsg = " 1 document upload failed."
                        elif results[1] > 1 :
                                failmsg = " %d document uploads failed." % (results[1],)
                        else :
                                failmsg = ""
                        displayMessage("Uploads Successful", "Successfully uploaded %d documents.%s" % (results[0], failmsg))
	else :
		cmd = CocoaDialog + " fileselect --title \"Select File to Upload\""
		filename = commands.getoutput(cmd)
                url = uploadDocument(filename, credentials)
                goToDoc(url)

if __name__ == "__main__":
    main()